﻿<?PHP
require_once("base.wpfb.php");
require_once ('src/facebook.php');

class CrawlManager{

private $globalVars = null;
private $entryPageName = null;

public function __construct($pageParent) {
	$this->globalVars = new WPFB(plugin_dir_url(__FILE__));
	$this->entryPageName = $pageParent;
}

public function pushToDatabase()
{
	try{
		//$responseData = json_decode($_POST['data'], true);
		$time1 = round(microtime(true) * 1000);
		$responseData = $_POST['data'];
		$groupId = $_GET['group_id'];
		$k = (object) $responseData;
		
		$i = $this->globalVars->insert_BNCVUKERJSFQWUIR($k, $groupId);
		$time = round(microtime(true) * 1000) - $time1;
		echo "$i rows inserted in $time ms";
	}catch(Exception $e)
	{
		header( 'HTTP/1.1 400 BAD REQUEST' );
		$this->globalVars->printException($e);
	}
	die;
}

public function crawlerFrontEnd()
{
	try{
		//throw new Exception("wokring...");
		$groupList = $this->globalVars->select_VMLOYTKSDVFLGDLGLD();
		if(count($groupList) == 0)
			throw new Exception("No group exists in database. Please insert atleast one group.");
		$this->crawlerFrontEnd_UI($groupList, null, 'now');
	}catch(Exception $e)
	{ 
		$this->globalVars->printException($e);
		// No UI because with error in database we cannot do anything meaningfull.
	}
}
private function crawlerFrontEnd_UI($groupList, $accessToken, $showValueForEpocTime)
{ 
?>
<h1>Choose the group id</h1>
<strong>Group-id:</strong>
<?PHP
echo "<select name='show_group_id' id='show_group_id'>";
foreach($groupList as $rows)
{
	echo "<option value='{$rows['group_id']}'>{$rows['name']}</option>";
}
echo "</select>";
?>

<script type='text/javascript' src='//datejs.googlecode.com/files/date.js'></script>
<br/>
<strong>Until:</strong> <input type="text" id='given_epoc' class='big-text' size='40' value="<?PHP echo $showValueForEpocTime; ?>" tabindex='2' 
onfocus='this.select()' noBanglaText='noBanglaText'/> <abbr style='cursor:help' title='now, yesterday, 08 May 2013 08:00:30 am, 23:59:00 etc'>Help?</abbr>

<br/><br/>
<button id='startCrawl' class='button button-primary'>Start</button>
	
<script type='text/javascript'>
function CrawlManager(){
}
CrawlManager.prototype = {
	"apiNextUrl" : null
};
CrawlManager.prototype.commonGroupName = null;
CrawlManager.prototype.commonGroupId = null;
CrawlManager.prototype.commonAccessToken = null;
CrawlManager.prototype.apiDataFetchCount = 0;
CrawlManager.prototype.localServerUrl = "<?php echo get_bloginfo('wpurl') . '/wp-admin/admin-ajax.php?action=wpfb_crawler'?>";
CrawlManager.prototype.totalApiCall = 0;

CrawlManager.prototype.initiateApiCall = function(url){
	this.apiNextUrl = url;
	this.apiCall(this.apiNextUrl);
}

CrawlManager.prototype.apiCall=function(url){
	var root = this;
	if( this.apiNextUrl == null)
		return;
		
	(function($){
		$.get(url)
		.done(function(responseData){
			var json = $.parseJSON(responseData);
			
			if( json.data.length > 0)
			{
				root.apiNextUrl = json.paging.next;
				//root.print_r("Success [Api]","Data fetched count = "+json.data.length);
				root.apiDataFetchCount += json.data.length;
			}
			else
			{
				root.apiNextUrl = null;
				root.print_r("Success [Api Call]","Data fetch completed at "+new Date().toLocaleString());
				return;
			}
			root.localCall(json);
		})
		.fail(function(jqxhr,textStatus,error) {
			var err = textStatus + " >>Description: " + jqxhr.getAllResponseHeaders() + " >> Time: " + new Date();
			root.print_r("Request Failed [Api Call]", err);
		});
	})(jQuery);
}
CrawlManager.prototype.localCall=function(data){
	var root = this;
	(function($){
		$.post(root.localServerUrl+'&group_id='+root.commonGroupId+'', {data:data})
		.done(function(responseData){
			root.print_r("Success [LocalServer]",responseData);
			root.logCall();
		})
		.fail(function( jqxhr, textStatus, error ) {
			var err = textStatus + " >>Description: " + jqxhr.responseText + " >> Time: " + new Date();
			root.print_r("Request Failed [LocalServer Call]",err);
		});
	})(jQuery);
}
CrawlManager.prototype.logCall=function(){
	++this.totalApiCall;
	this.print_r("In progress >> [" + this.commonGroupName + "]" , "Total entries saved so far = "+ this.apiDataFetchCount);
	this.apiCall(this.apiNextUrl);
}

CrawlManager.prototype.print_r = function(status, printthis) {
    var output = '';

    if(typeof(printthis) == 'Array' || typeof(printthis) == 'object') {
        for(var i in printthis) {
            output += i + ' : ' + print_r(printthis[i], true) + '\n';
        }
    }else {
        output += printthis;
    }
	
	jQuery('#localServerResponseData_viewer').prepend('<pre><strong>'+status+'</strong>: '+output+'</pre>');
	//return output;
};

(function ($){
	$("#startCrawl").click(function(){
		// prepare data
		var $groupId = $('#show_group_id');
		
		var accessToken = "<?PHP echo $this->globalVars->facebook->getAccessToken(); ?>";
		
		var $inputButton= $("#given_epoc");
		$inputButton.val( Date.parse($inputButton.val()) );
		
		var epoc= new Date($inputButton.val()).getTime();
			epoc /= 1000;
		
		var url = "https://graph.facebook.com/v2.0/";
		url += $groupId.val() +"/feed?fields=likes.limit(1).summary(true),comments.limit(1).summary(true),from,message,type,picture,link,id,updated_time,created_time";
		url += "&limit=400&until="+epoc;
		url += "&access_token="+accessToken;
		url += "=?";
		
		//console.log(url);
		var crawler = new CrawlManager();
		crawler.apiNextUrl = url;
		crawler.commonGroupId = $groupId.val();
		crawler.commonGroupName = $groupId['0'].options[$groupId['0'].selectedIndex].text;
		crawler.print_r(crawler.commonGroupName, "Data fetch started at "+ new Date().toLocaleString() + "<hr/>");
		crawler.apiCall(url);
	});
})(jQuery);
</script>	
<hr/>
<div id='localServerResponseData_viewer'></div>
<?PHP 
} // function_UI ends here
} // class ends here
?>